<template>
  <div class="example-tb">
    <el-alert
      title="table从后台api加载数据源"
      type="warning"
      show-icon
      :closable="false"
    >
      <p>
        1、只需要配置好列信息即可从后台加载(自动求和见代码中的备注说明或table组件api)。
      </p>
      <p>
        2、如果需要筛选条件，在loadTableBefore方法中按demo格式提交查询参数即可
      </p>
      <p>
        3、具体使用见：框架文档->组件api->voltable。<a
          href="http://v2.volcore.xyz/document/api"
          target="_blank"
          >点击查看文档
        </a>
      </p>
    </el-alert>
    <div class="tb">
      <div class="search-info">
        <vol-form
          :label-width="80"
          ref="myform"
          class="my-form"
          :formFields="searchFields"
          :formRules="formOptions"
        >
        </vol-form>
        <div class="btns">
          <el-button
            v-if="false"
            type="danger"
            size="small"
            @click="getSelectRows"
            >获取选中行</el-button
          >
          <el-button type="primary" size="small" @click="addRow"
            ><i class="el-icon-plus"></i>添加行</el-button
          >
          <el-button type="danger" ghost @click="del">删除行</el-button>
          <el-button type="primary" size="small" @click="search"
            ><i class="el-icon-search"></i>搜索</el-button
          >
        </div>
      </div>
      <vol-table
        ref="table"
        :columns="columns"
        :pagination-hide="false"
        :max-height="400"
        :url="url"
        :index="true"
        :single="false"
        @loadBefore="loadTableBefore"
        @loadAfter="loadTableAfter"
        @endEditBefore="endEditBefore"
        :beginEdit="beginEdit"
      ></vol-table>
    </div>
  </div>
</template>
<script>
import VolTable from "@/components/basic/VolTable.vue";
import VolForm from "@/components/basic/VolForm.vue";
export default {
  components: { VolTable, VolForm },
  created() {},
  data() {
    return {
      //查询条件字段
      searchFields: {
        Name: "",
        CreateDate: [],
        CategoeyId: null,
      },
      formOptions: [
        //表单配置见表单组件文档
        [
          {
            title: "产品名",
            field: "Name",
            placeholder: "模糊查询",
          },
          {
            title: "产品类型",
            field: "CategoeyId",
            dataKey: "产品类型",
            placeholder: "产品类型",
            data: [],
            type: "select",
          },
          {
            title: "创建时间",
            range: true,
            colSize: 6,
            field: "CreateDate",
            type: "date",
            onChange: (val) => {},
          },
        ],
      ],
      viewModel: false, //点击单元格时弹出框
      url: "api/app_product/getPageData", //后从加载数据的url
      columns: [
        {
          field: "Id",
          title: "主键ID",
          type: "string",
          width: 90,
          hidden: true,
          readonly: true,
          require: true,
        },
        {
          field: "Name",
          title: "产品名",
          type: "string",
          width: 90,
          fixed: true,
          require: true,
          edit: { type: "text" },
        },
        {
          field: "CategoeyId",
          title: "分类",
          type: "int",
          fixed: true,
          bind: { key: "产品类型", data: [] },
          width: 110,
          edit: { type: "select" },
        },
        {
          field: "Enable",
          title: "是否可用",
          type: "int",
          bind: { key: "enable", data: [] },
          width: 80,
          edit: { type: "switch" },
        },
        {
          field: "CreateDate",
          title: "提交时间",
          type: "datetime",
          width: 130,
        },
        { field: "操作", title: "操作", width: 150, render: this.getRender() },
      ],
    };
  },
  methods: {
    //点击查询时生成查询条件
    loadTableBefore(param, callBack) {
      console.log("加载数据前" + param);
      //生成查询条件
      param.wheres = [
        //设置为like模糊查询
        {
          name: "Name",
          value: this.searchFields.Name,
          displayType: "like",
        },
        {
          name: "CategoeyId",
          value: this.searchFields.CategoeyId,
        },
        {
          name: "CreateDate",
          value: this.searchFields.CreateDate[0],
          displayType: "thanorequal", //>=
        },
        {
          name: "CreateDate",
          value: this.searchFields.CreateDate[1],
          displayType: "lessorequal", //<=
        },
      ];
      callBack(true); //此处必须进行回调，返回处理结果，如果是false，则不会执行后台查询
    },
    loadTableAfter(data, callBack) {
      //此处是从后台加数据后，你可以在渲染表格前，预先处理返回的数据
      console.log("加载数据后" + data);
      callBack(true); //同上
    },
    search() {
      this.$refs.table.load();
    },
    addRow() {
      //添加行
      this.$refs.table.addRow({});
    },
    del() {
      let rows = this.$refs.table.getSelected();
      if (rows.length == 0) {
        return this.$message.error("请先选中行");
      }
      var aryids = [];
      rows.forEach(function(item, index, arr) {
        aryids.push(item.Id);
      });

      //this.$refs.table.delRow();
      //此处可以接着写删除后台的代码
      let tigger = false;

      this.$confirm("删除警告?", "确认要删除选择的数据吗", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        if (tigger) return;
        tigger = true;
        //this.$refs.table.delRow();
        this.http
          .post("/api/app_product/del", aryids, "正在删除数据....")
          .then((x) => {
            if (!x.status) return this.$message.error(x.message);
            this.$message.success(x.message);
            this.search();
          });
      });
    },
    getSelectRows() {
      let rows = this.$refs.table.getSelected();
      if (rows.length == 0) {
        return this.$message.error("请先选中行1");
      }
      let text = "当前选中的行数据：" + JSON.stringify(rows);
      this.$Message.info(text);
    },
    endEditBefore(row, column, index) {
      //可以自动结束编辑时，自动执行保存，下面getRender的保存按钮去掉
      // this.editSave();
      return true;
    },
    beginEdit(row, column, index) {
      //编辑前将购买类型转换成数字，否则与字典的类型对应不上绑定不了默认值
      //row.CowType = row.CowType * 1;
      return true;
    },
    editSave(row) {
      //调用框架的默认保存方法
      if (
        row.Id != undefined &&
        row.Id != null &&
        row.Id != "" &&
        row.Id != "0"
      ) {
        this.http
          .post("/api/app_product/update", { mainData: row }, true)
          .then((x) => {
            this.$Message.info("更新成功");
            console.log("保存结果：" + JSON.stringify(x));
          });
      } else {
        this.http
          .post("/api/app_product/add", { mainData: row }, true)
          .then((x) => {
            this.$Message.info("新增成功");
            console.log("保存结果：" + JSON.stringify(x));
          });
      }
    },
    getRender() {
      return (h, { row, column, index }) => {
        return (
          <div
            onClick={($e) => {
              $e.stopPropagation();
            }}
          >
            <el-button
              onClick={($e) => {
                this.tableData.splice(index, 1);
              }}
              type="primary"
              plain
              size="small"
              style="padding: 10px !important;"
            >
              删除
            </el-button>
            <el-button
              onClick={($e) => {
                $e.stopPropagation();
                //强制结束编辑
                this.$refs.table.edit.rowIndex = -1;
                //执行保存方法
                this.editSave(row);
              }}
              type="success"
              plain
              size="small"
              style="padding: 10px !important;"
            >
              保存
            </el-button>

            <el-dropdown
              type="primary"
              split-button
              trigger="click"
              style="padding-left: 10px !important;"
              v-slots={{
                dropdown: () => (
                  <el-dropdown-menu>
                    <el-dropdown-item>
                      <div
                        onClick={($e) => {
                          this.$Message.info("京酱肉丝");
                        }}
                      >
                        京酱肉丝
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <div
                        onClick={($e) => {
                          this.$Message.info("驴肉火烧");
                        }}
                      >
                        驴肉火烧
                      </div>
                    </el-dropdown-item>
                    <el-dropdown-item>
                      <div
                        onClick={($e) => {
                          this.$Message.info("吊炉烤鸭");
                        }}
                      >
                        吊炉烤鸭
                      </div>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                ),
              }}
            >
              更多
            </el-dropdown>
          </div>
        );
      };
    },
  },
};
</script>
<style lang="less" scoped>
.example-tb {
  padding: 15px;
}
.tb {
  margin-top: 15px;
}
.v-header {
  background: white;
  padding: 10px;
}
.search-info {
  display: flex;
  .my-form {
    width: 840px !important;
    margin-bottom: -15px;
  }
  .btns {
    margin-left: 15px;
    position: relative;
    margin-top: 2px;
  }
}
</style>
